package com.wskj.common.utils.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wskj.common.utils.common.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class SenInfoCheckUtil {

    private static Logger logger = LoggerFactory.getLogger(SenInfoCheckUtil.class);

    private static String MpAccessToken;

    /**
     * 获取Token  小程序
     * @param
     * @param
     * @return AccessToken
     */
    public static String getMpToken(String appid,String appSecret){
        return getMpAccessToken(appid,appSecret);
    }

    public static void sendMsg(String wxId, String templateId, String page, List<String> msgList,String appid,String appSecret){
        String mpToken = getMpToken( appid,appSecret);
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" +mpToken;
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(wxId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(templateId);//订阅消息模板id
        // 退款、用户未读、商家未读 都跳转到消息页面
        wxMssVo.setPage("/pages/msg/index");
        wxMssVo.setData(getParam(msgList));
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        String body = responseEntity.getBody();
        logger.info("=========消息模板========="+templateId);
        logger.info("=========订阅发送消息后结果========="+body);
    }

    /**
     * 获取access_token
     * 每个两个小时自动刷新AcessTocken
     */

    public static String getMpAccessToken(String appid,String appSecret){
        String jsonResult = HttpClientUtil.doPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret);
        JSONObject parseObject = JSON.parseObject(jsonResult);
        logger.info("=========accessTokenOut========="+parseObject.toJSONString());

        String errcode = parseObject.getString("errcode");
        String accessToken = parseObject.getString("access_token");
        String expiresIn = parseObject.getString("expires_in");
        return accessToken;
    }

    public static Map<String, TemplateParam> getParam(List<String> msgList){
        Map<String, TemplateParam> paras = new HashMap<>(3);
        paras.put("character_string22",new TemplateParam(msgList.get(0)));
        paras.put("thing29",new TemplateParam( msgList.get(1)));
        paras.put("number47",new TemplateParam( msgList.get(2)));
        paras.put("time10",new TemplateParam( msgList.get(3)));
        paras.put("thing19",new TemplateParam( msgList.get(4)));
        return paras;
    }
}
